const {debug} = require("console")
const {readdirSync, readFileSync, write, writevSync, writeFileSync} = require("fs")
const {homedir} = require("os")
const {extname, basename, join} = require("path")


const isDebug = process.argv.length > 2

function getSnip(idx,name,code){
return `
			<entry${idx}>
				<LANGUAGE>
					<str>
						<![CDATA[C/C++]]>
					</str>
				</LANGUAGE>
				<NAME>
					<str>
						<![CDATA[${name}]]>
					</str>
				</NAME>
				<CODE>
					<str>
						<![CDATA[${code.replaceAll('\n','\\n')}]]>
					</str>
				</CODE>
			</entry${idx}>
`
}

var snips = readdirSync(__dirname).filter( name => extname(name) == '.snip')
var entryCount=0
var allSnips = ''
for(let snip of snips){
  allSnips += getSnip(
    ++entryCount,
    snip.split(".")[0]
    ,readFileSync(join(__dirname,snip),{encoding:'utf8'})
  )
}

allSnips = `
<auto_complete>
${allSnips}
</auto_complete>
`

//writeFileSync(join(__dirname,"../autoComple.conf"), allSnips,{encoding:'utf8'})
//replace default.conf
let defaultConfigPaht = join(homedir(),'.config/codeblocks/default.conf')
let defaultConfig = readFileSync(defaultConfigPaht,{encoding:'utf8'})
console.log( '读取codeblocks 默认配置成功，位置：',defaultConfigPaht )

if( isDebug ){
  console.log( allSnips )
  process.exit()
}

writeFileSync(defaultConfigPaht+'.bak',defaultConfig,{encoding:'utf8'})
console.log( '备份配置到 ',defaultConfigPaht+'.bak' )

writeFileSync(defaultConfigPaht,defaultConfig.replace(/<auto_complete>[\s\S]+<\/auto_complete>/, allSnips),{encoding:'utf8'})

console.log( '写入 auto_complete 成功!' )
console.log( `
如果你打开始codeblocks 提示有失败，你可以执行下面的命令
cp ${defaultConfigPaht+'.bak'} ${defaultConfigPaht}
恢复原来的配置

恢复配置后，也可以打开 codeCompleteSnip/ 下的每一个*.snip 文件手动添加

` )

//console.log(   defaultConfig.replace(/<auto_complete>[\s\S]+<\/auto_complete>/, allSnips) )
